#!/usr/bin/env python
# encoding: utf-8

import time
import json
import logging
import threading
import hashlib
import os
import random
from datetime import datetime

from apscheduler.jobstores.memory import MemoryJobStore
from django.db import connections
from django.forms.models import model_to_dict
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.executors.pool import ThreadPoolExecutor
from fly2018.db_conf import magic_redis, redis_host, redis_port, redis_pwd, redis_db_name
from apps.magic_models import MagicMockProfit
from fly2018 import db_conf
from fly2018.logging_conf import log_common

logger = logging.getLogger(__name__)

db_time_format = "%Y-%m-%d %H:%M:%S"

executors = {
    'default': ThreadPoolExecutor(5)
}

redis_args = {
    'host': redis_host,
    'port': redis_port,
    'db': redis_db_name,
    'password': redis_pwd
}

# redis_job_store =
# RedisJobStore(jobs_key='_apscheduler.jobs', run_times_key='sync_apscheduler.run_times', **redis_args)
memory_job_store = MemoryJobStore()
scheduler = BackgroundScheduler(executors=executors)
scheduler.add_jobstore(memory_job_store, "default")

"""
产生广告收益模拟数据
日期、自动生成， 格式为：2019-02-14
广告位、固定名称：咪咕阅读APP焦点图
广告位ID、固定名称：ID:256472
展示数、公式生成：计算公式：当日收益除以2
点击数、公式生成：计算公式：展示数*点击率（点击率随机在千分之7-9之间生成。）
eCPM（元）、固定：2.00元
当日收益（元）、动态生成：在800.00-1300.00元之间，随机取数，精确到小数点两位。
"""


def md5(md5_char):
    """
    md5算法
    :param md5_char:
    :return:
    """
    hash_md5 = hashlib.md5(md5_char.encode("utf-8"))
    return hash_md5.hexdigest()


class CreateSchedulerWork(threading.Thread):
    def __init__(self, scheduler):
        super(CreateSchedulerWork, self).__init__()
        self.scheduler = scheduler
        self.setDaemon(True)

    def run(self):

        adv_ids = {"256472": "咪咕阅读APP焦点图", "264659": "新闻H5页面"}
        while True:
            try:

                for k, v in adv_ids.items():
                    dt = datetime.now()
                    dt_format = dt.strftime('%Y-%m-%d')

                    per_profit = round(random.uniform(2, 3), 2)
                    adv_views = int(per_profit * 200)
                    adv_clicks = int((adv_views * random.uniform(7, 9)) / 1000)
                    r_p_key = "{}_{}".format(k, dt_format)
                    if magic_redis.hkeys(r_p_key):
                        profit = magic_redis.hget(r_p_key, "profit")
                        per_profit = per_profit + float(profit)
                        adv_views = adv_views + int(magic_redis.hget(r_p_key, "views"))
                        adv_clicks = adv_clicks + int(magic_redis.hget(r_p_key, "clicks"))
                        magic_redis.hmset("{}_{}".format(k, dt_format),
                                          {"profit": per_profit, "views": adv_views, "clicks": adv_clicks})
                    else:
                        profit_view_click = {"profit": per_profit,
                                             "views": adv_views,
                                             "clicks": adv_clicks}
                        magic_redis.hmset("{}_{}".format(k, dt_format), profit_view_click)

                    if adv_clicks <= 0:
                        per_profit = 0

                    mp_results = MagicMockProfit.objects.filter(adv_date=dt_format, adv_id=k)
                    if not mp_results:
                        MagicMockProfit.objects.create(adv_id=k, adv_views=adv_views,
                                                       adv_clicks=adv_clicks, adv_eCPM=2, adv_profit=per_profit,
                                                       adv_date=dt_format, is_deleted=0)
                    else:
                        MagicMockProfit.objects.filter(adv_date=dt_format, adv_id=k).update(
                            adv_views=adv_views, adv_clicks=adv_clicks, adv_profit=per_profit)

            except Exception as ex:
                import traceback
                log_common.error("产生广告收益模拟数据", ex)
                log_common.error("产生广告收益模拟数据失败 = {}".format(traceback.format_exc()))
            finally:
                connections.close_all()
                time.sleep(3 * 60)


register_events(scheduler)
scheduler.start()
log_common.warn("产生广告收益模拟数据开始")
add_work = CreateSchedulerWork(scheduler)
add_work.start()
